import React, { useState, useRef, useEffect } from 'react';
import { Button, Input, Typography, Select, message, Avatar, Drawer } from 'antd';
import { SendOutlined, StarFilled, UserOutlined, SettingOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useCustomers } from '../hooks/useCustomers';
import type { Customer } from '../types';
import { v4 as uuid } from 'uuid';
import UniversalCard from '../components/UniversalCard';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { getManagerAvatar, getCustomerAvatar } from '../utils/avatarUtils';
import { authService } from '../lib/authService';
import { filterCustomersByRole } from '../utils/customerFilter';

const { Text } = Typography;
const {  } = Input;
const { Option } = Select;

// 消息接口 
interface Message {
  id: string;
  type: 'user' | 'advisor';
  content: string;
  timestamp: string;
  sender: string;
}

// WebSocket消息接口
interface WebSocketMessage {
  type: 'message' | 'typing' | 'stopTyping' | 'heartbeat' | 'pong' | 'conversation_update' | 'error' | 'connection_closed';
  sender_id?: string;
  recipient_id?: string;
  content?: string;
  timestamp?: string;
  conversation_id?: string;
  message?: string;
  uuid?: string;
}

// B端经理接口
interface Manager {
  id: string;
  name: string;
  specialty: string;
  is_online: boolean;
  connection_count: number;
  status: string;
}

export default function ClientTestPage() {

  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [currentCustomer, setCurrentCustomer] = useState<Customer | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [currentCWebSocket, setCurrentCWebSocket] = useState<WebSocket | null>(null);
  const [showQuickReplies, setShowQuickReplies] = useState(false);
  const [currentQuickReplies, setCurrentQuickReplies] = useState<string[]>([]);
  const [lastUserQuery, setLastUserQuery] = useState<string>(''); // 跟踪最后的用户查询
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 生成WebSocket用户ID的辅助函数
  const generateWebSocketUserId = (customer: Customer): string => {
    return `C_${customer.id}_${customer.name.replace(/\s+/g, '_')}`;
  };
  
  // B端经理相关状态
  const [managers, setManagers] = useState<Manager[]>([]);
  const [selectedManager, setSelectedManager] = useState<string>(''); // 不设默认值，动态选择第一个
  const [configDrawerVisible, setConfigDrawerVisible] = useState<boolean>(false);
  const [existingConversations, setExistingConversations] = useState<any[]>([]);

  // 防止重复调用的ref
  const isFetchingManagers = useRef(false);
  const isFetchingConversations = useRef(false);

  // 使用客户数据Hook
  const { customers: allCustomers } = useCustomers();
  const [customers, setCustomers] = useState<Customer[]>([]);
  
  // 仅供demo账户查看的客户列表


  // 保存和获取上次选择的客户ID
  const saveLastSelectedCustomer = (customerId: string) => {
    localStorage.setItem('lastSelectedCustomerId', customerId);
  };

  const getLastSelectedCustomer = (): string | null => {
    return localStorage.getItem('lastSelectedCustomerId');
  };

  // 获取当前登录的经理并过滤客户
  useEffect(() => {
    const manager = authService.getManager();
    if (manager) {
      // 默认理财经理为当前登录者
      setSelectedManager(manager.id);
    }
    
    // 根据用户角色过滤客户列表
    const filteredCustomers = filterCustomersByRole(allCustomers, manager?.name);
    setCustomers(filteredCustomers);
  }, [allCustomers]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      scrollToBottom();
    }, 0);
    return () => clearTimeout(timer);
  }, [messages]);

  // 监控 selectedManager 变化
  useEffect(() => {
    console.log('🎯 selectedManager 变化:', selectedManager, new Error().stack);
  }, [selectedManager]);

  // 初始化用户列表和选择客户（优先使用上次保存的选择）
  useEffect(() => {
    if (customers.length > 0 && !currentCustomer) {
      console.log('🔄 开始初始化客户选择，客户数量:', customers.length);
      
      // 优先尝试恢复上次选择的客户
      const lastSelectedCustomerId = getLastSelectedCustomer();
      let targetCustomer: Customer | null = null;
      
      if (lastSelectedCustomerId) {
        targetCustomer = customers.find(c => c.id.toString() === lastSelectedCustomerId) || null;
      }
      
      // 如果没有保存的选择或找不到对应客户，则使用第一个客户
      if (!targetCustomer) {
        targetCustomer = customers[0];
      }
      
      // 检查目标客户是否已经与当前经理有对话
      const targetCustomerWsId = generateWebSocketUserId(targetCustomer);
      
      if (selectedManager && checkExistingConversation(targetCustomerWsId, selectedManager)) {
        // 如果目标客户已经有对话，不自动选择任何客户，让用户自己选择
        message.info('请手动选择客户开始对话');
      } else {
        // 目标客户没有对话，直接选择
        setCurrentCustomer(targetCustomer);
        // 保存这次的选择
        saveLastSelectedCustomer(targetCustomer.id.toString());
      }
    }
  }, [customers, currentCustomer, selectedManager, existingConversations]);

  // 获取可用的B端经理列表和现有对话 - 只在组件挂载时执行一次
  useEffect(() => {
    console.log('🚀 组件挂载，初始化数据');
    fetchAvailableManagers();
    fetchExistingConversations();
    
    // 移除30秒定时刷新，改为只在打开配置抽屉时刷新，减少不必要的API调用
  }, []); // 保持空依赖数组，只在组件挂载时执行一次

  const fetchAvailableManagers = async () => {
    // 防止重复调用
    if (isFetchingManagers.current) {
      console.log('⏳ fetchAvailableManagers 已在执行中，跳过');
      return;
    }
    isFetchingManagers.current = true;

    try {
      const response = await fetch('/api/managers/available');
      const result = await response.json();
      if (result.success) {
        let mgrs: Manager[] = result.data;

        // 如果当前选中的经理不在返回列表中（可能因为离线而未返回），则将其追加到列表，以便保持显示
        if (selectedManager && !mgrs.find((m: Manager) => m.id === selectedManager)) {
          // 使用authService.getManager()确保与ProtectedRoute的认证逻辑一致
          const storedManager = authService.getManager();
          if (storedManager) {
            mgrs = [
              ...mgrs,
              {
                id: storedManager.id,
                name: storedManager.name,
                specialty: '理财师',
                is_online: false,
                connection_count: 0,
                status: '离线'
              } as Manager
            ];
          }
        }

        setManagers(mgrs);

        // 移除自动选择逻辑，只更新经理列表，不改变当前选择
      } else {
        console.error('获取经理列表失败:', result.message);
      }
    } catch (error) {
      console.error('Error fetching managers:', error);
    } finally {
      isFetchingManagers.current = false;
    }
  };

  // 获取现有对话列表
  const fetchExistingConversations = async () => {
    // 防止重复调用
    if (isFetchingConversations.current) {
      console.log('⏳ fetchExistingConversations 已在执行中，跳过');
      return;
    }
    isFetchingConversations.current = true;

    try {
      const response = await fetch('/api/conversations/list');
      
      // 检查响应状态
      if (!response.ok) {
        console.error('API请求失败:', response.status, response.statusText);
        setExistingConversations([]);
        return;
      }
      
      // 检查响应内容类型
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        console.error('API返回非JSON数据:', contentType);
        setExistingConversations([]);
        return;
      }
      
      const result = await response.json();
      if (result.success) {
        setExistingConversations(result.data || []);
      } else {
        console.error('获取对话列表失败:', result.message);
        setExistingConversations([]);
      }
    } catch (error) {
      console.error('Error fetching conversations:', error);
      setExistingConversations([]);
    } finally {
      isFetchingConversations.current = false;
    }
  };

  // 检查是否已存在对话
  const checkExistingConversation = (customerId: string, managerId: string): boolean => {
    return existingConversations.some(conv => 
      conv.c_user_id === customerId && conv.b_user_id === managerId
    );
  };

  // 创建会话
  const createChatSession = async (customerId: string, managerId: string) => {
    try {
      const response = await fetch('/api/sessions/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          c_user_id: customerId,
          b_manager_id: managerId,
        }),
      });

      const result = await response.json();
      if (result.success) {
        return true;
      } else {
        console.error('会话创建失败:', result.message);
        return false;
      }
    } catch (error) {
      console.error('Error creating session:', error);
      return false;
    }
  };

  // 设置全局购买产品函数
  useEffect(() => {
    (window as any).buyProduct = handleBuyProduct;
    (window as any).buyAllocation = handleBuyAllocation;
    
    return () => {
      delete (window as any).buyProduct;
      delete (window as any).buyAllocation;
    };
  }, []);

  const generateMessageId = () => {
    return Date.now().toString() + Math.random().toString(36).substr(2, 9);
  };

  // 获取用户风险等级显示文本
  const getRiskLevelText = (user: Customer): string => {
    return user.risk_level || '未知';
  };

  // 发送断开连接消息的公共方法
  const sendDisconnectMessage = (ws: WebSocket, userId: string, userName: string, reason: string, _isAbnormal: boolean = false) => {
    if (ws && ws.readyState === WebSocket.OPEN) {
      try {
        const disconnectMessage: WebSocketMessage = {
          type: 'connection_closed',
          sender_id: userId,
          recipient_id: selectedManager,
          content: `用户 ${userName} ${reason}`,
          timestamp: new Date().toISOString(),
          uuid: (ws as any).connectionUuid
        };
        ws.send(JSON.stringify(disconnectMessage));  
      } catch (error) {
        console.error(`Failed to send disconnect message:`, error);
      }
    }
    
    // 清理心跳定时器
    if ((ws as any).heartbeatInterval) {
      clearInterval((ws as any).heartbeatInterval);
      delete (ws as any).heartbeatInterval;
    }
  };

  // 建立C端WebSocket连接
  const connectAsClient = async (customer: Customer) => {
    // 关闭现有连接
    if (currentCWebSocket) {
      const oldWsUserId = currentCustomer ? generateWebSocketUserId(currentCustomer) : '';
      sendDisconnectMessage(currentCWebSocket, oldWsUserId, currentCustomer?.name || '', '断开连接');
      currentCWebSocket.close();
    }

    // 使用 C_{id}_{name} 格式创建WebSocket用户ID，增加可读性
    const wsUserId = generateWebSocketUserId(customer);
    
    if (!wsUserId) {
      message.error(`无法找到用户 ${customer.name} 的WebSocket ID`);
      return;
    }

    // 创建会话（使用新格式的WebSocket用户ID）
    if (selectedManager) {
      const sessionCreated = await createChatSession(wsUserId, selectedManager);
      if (!sessionCreated) {
        message.error('创建会话失败，无法建立连接');
        return;
      }
      // 创建会话成功后刷新对话列表
      fetchExistingConversations();
    }

    try {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      // 每次连接都生成全新的UUID，确保多页面时每个连接都是唯一的
      const connectionUuid = uuid();
      const wsUrl = `${protocol}//${window.location.host}/ws/${wsUserId}?uuid=${encodeURIComponent(connectionUuid)}`;
      
      console.log(`🚀 准备建立WebSocket连接: ${customer.name} (${wsUserId}) - UUID: ${connectionUuid}`); 
      
      const newWs = new WebSocket(wsUrl);

      // 将uuid保存到WebSocket对象上，方便断开连接时使用
      (newWs as any).connectionUuid = connectionUuid;

      newWs.onopen = () => {
        console.log(`🔗 WebSocket连接成功: ${customer.name} (${wsUserId}) - UUID: ${connectionUuid}`);
        setIsConnected(true);
        message.success(`已连接到客户: ${customer.name}`);
      };

      newWs.onmessage = (event) => {
        try {
          const wsMessage: WebSocketMessage = JSON.parse(event.data); 
          console.log('📨 收到WebSocket消息:', wsMessage);
          console.log('🎯 当前选中的经理:', selectedManager);
          console.log('🔍 消息sender_id:', wsMessage.sender_id);
          console.log('✅ 是否匹配:', wsMessage.sender_id === selectedManager);
          
          if (wsMessage.type === 'message' && wsMessage.sender_id === selectedManager) {
            console.log('✅ 匹配成功，处理消息');
            // B端经理发来的消息           
            const managerInfo = managers.find(m => m.id === selectedManager);
            const advisorMessage: Message = {
              id: generateMessageId(),
              type: 'advisor',
              content: wsMessage.content || '',
              timestamp: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
              sender: managerInfo ? managerInfo.name : 'B端经理'
            };
                       
            setMessages(prev => [...prev, advisorMessage]);
            console.log('💬 已添加消息到界面:', advisorMessage);
            
            // 检查是否需要显示快捷回复（异步调用，不阻塞）
            if (wsMessage.content) {
              checkAndSetQuickReplies(wsMessage.content, lastUserQuery).catch(error => {
                console.error('快捷回复生成失败:', error);
              });
            }
          } else {
            console.log('❌ 消息不匹配条件:', {
              isMessage: wsMessage.type === 'message',
              senderId: wsMessage.sender_id,
              selectedManager: selectedManager,
              isMatch: wsMessage.sender_id === selectedManager
            });
          }
        } catch (error) {
          console.error('Error parsing WebSocket message:', error);
        }
      };

      newWs.onclose = (event) => {
        console.log(`❌ WebSocket连接关闭: ${customer.name} (${wsUserId}) - Code: ${event.code}, UUID: ${connectionUuid}`);
        setIsConnected(false);
        
        // 清理心跳定时器
        if ((newWs as any).heartbeatInterval) {
          clearInterval((newWs as any).heartbeatInterval);
          delete (newWs as any).heartbeatInterval;
        }
        
        // 如果连接异常关闭，尝试发送connection_closed消息
        if (event.code !== 1000) { // 1000是正常关闭
          sendDisconnectMessage(newWs, wsUserId, customer.name, `连接异常断开 (code: ${event.code})`, true);
        }
      };

      newWs.onerror = (error) => {
        console.error(`WebSocket error for customer ${customer.name}:`, error);
        setIsConnected(false);
        message.error('WebSocket连接错误');
      };

      setCurrentCWebSocket(newWs);

      // 设置心跳
      const heartbeatInterval = setInterval(() => {
        if (newWs.readyState === WebSocket.OPEN) {
          newWs.send(JSON.stringify({
            type: 'heartbeat',
            sender_id: wsUserId,
            timestamp: new Date().toISOString()
          }));
        } else {
          clearInterval(heartbeatInterval);
        }
      }, 5000);

      // 将心跳定时器保存到WebSocket对象上，方便清理
      (newWs as any).heartbeatInterval = heartbeatInterval;

    } catch (error) {
      console.error('Error connecting to WebSocket:', error);
      message.error('连接失败');
    }
  };

  // 当用户或经理变化时，建立新的WebSocket连接
  useEffect(() => {
    if (currentCustomer && selectedManager) {
      connectAsClient(currentCustomer);
    }

    return () => {
      if (currentCWebSocket) {
        // 发送断开连接消息
        const cleanupWsUserId = currentCustomer ? generateWebSocketUserId(currentCustomer) : '';
        sendDisconnectMessage(currentCWebSocket, cleanupWsUserId, currentCustomer?.name || '', '断开连接');
        currentCWebSocket.close();
      }
    };
  }, [currentCustomer, selectedManager]);

  // 处理用户切换
  const handleUserChange = (userId: string) => {
    const newCustomer = customers.find(user => user.id.toString() === userId);
    if (newCustomer && newCustomer.id.toString() !== currentCustomer?.id.toString()) {
      // 检查新客户是否已经与当前选中的经理有对话（使用新格式WebSocket用户ID）
      const newCustomerWsId = generateWebSocketUserId(newCustomer);
      if (selectedManager && checkExistingConversation(newCustomerWsId, selectedManager)) {
        const managerInfo = managers.find(m => m.id === selectedManager);
        message.error(`客户 ${newCustomer.name} 已经在与理财师 ${managerInfo?.name || selectedManager} 对话中，请勿重复创建对话`);
        return;
      }

      setCurrentCustomer(newCustomer);
      setMessages([]); // 清空对话列表
      setShowQuickReplies(false); // 隐藏快捷回复
      setCurrentQuickReplies([]); // 清空快捷回复选项
      setLastUserQuery(''); // 清空用户查询
      
      // 保存用户选择
      saveLastSelectedCustomer(newCustomer.id.toString());
      
      // 刷新对话列表
      fetchExistingConversations();
      
      message.info(`已切换到客户：${newCustomer.name}`);
    }
  };

  // 处理经理切换
  const handleManagerChange = (managerId: string) => {
    if (managerId !== selectedManager) {
      const managerInfo = managers.find(m => m.id === managerId);

      // 离线经理不可选择
      if (managerInfo && !managerInfo.is_online) {
        message.warning(`理财师 ${managerInfo.name} 当前不在线，无法选择`);
        return;
      }

      setSelectedManager(managerId);
      setMessages([]); // 清空对话列表
      setShowQuickReplies(false); // 隐藏快捷回复
      setCurrentQuickReplies([]); // 清空快捷回复选项
      setLastUserQuery(''); // 清空用户查询
      message.info(`已切换到理财师：${managerInfo ? managerInfo.name : managerId}`);
    }
  };

  // 发送消息
  const handleSendMessage = () => {
    if (!inputValue.trim() || !currentCustomer || !currentCWebSocket) return;

    if (!isConnected || currentCWebSocket.readyState !== WebSocket.OPEN) {
      message.error('WebSocket未连接，无法发送消息');
      return;
    }

    // 添加用户消息到界面
    const userMessage: Message = {
      id: generateMessageId(),
      type: 'user',
      content: inputValue,
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
      sender: currentCustomer.name
    };

    setMessages(prev => [...prev, userMessage]);
    setLastUserQuery(inputValue); // 保存用户查询用于生成快捷回复

    // 发送消息到B端经理
    try {
      const wsUserId = generateWebSocketUserId(currentCustomer);
      const messageData: WebSocketMessage = {
        type: 'message',
        sender_id: wsUserId, // 使用C端用户ID作为发送者
        recipient_id: selectedManager, // 发送给选中的B端经理
        content: inputValue,
        timestamp: new Date().toISOString()
      };

      currentCWebSocket.send(JSON.stringify(messageData)); 
    } catch (error) {
      console.error('Failed to send message:', error);
      message.error('发送消息失败');
    }

    setInputValue('');
    setShowQuickReplies(false); // 发送消息后隐藏快捷回复
    setCurrentQuickReplies([]); // 清空快捷回复选项
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 处理购买产品
  const handleBuyProduct = (_productId: string, _productName: string) => {
    // 这里可以添加实际的购买逻辑
  };

  // 处理购买资产配置
  const handleBuyAllocation = (allocationData: any) => {
    message.info(`正在为您配置资产组合：${allocationData.title}`);
    // 这里可以添加实际的购买逻辑
  };

  // 处理快捷回复点击 - 直接发送消息
  const handleQuickReply = (replyText: string) => {
    if (!currentCustomer || !currentCWebSocket) return;

    if (!isConnected || currentCWebSocket.readyState !== WebSocket.OPEN) {
      message.error('WebSocket未连接，无法发送消息');
      return;
    }

    // 添加用户消息到界面
    const userMessage: Message = {
      id: generateMessageId(),
      type: 'user',
      content: replyText,
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
      sender: currentCustomer.name
    };

    setMessages(prev => [...prev, userMessage]);
    setLastUserQuery(replyText); // 保存快捷回复内容用于后续生成

    // 发送消息到B端经理
    try {
      const wsUserId = generateWebSocketUserId(currentCustomer);
      const messageData: WebSocketMessage = {
        type: 'message',
        sender_id: wsUserId,
        recipient_id: selectedManager,
        content: replyText,
        timestamp: new Date().toISOString()
      };

      currentCWebSocket.send(JSON.stringify(messageData)); 
    } catch (error) {
      console.error('Failed to send quick reply:', error);
      message.error('发送消息失败');
    }

    // 隐藏快捷回复
    setShowQuickReplies(false);
    setCurrentQuickReplies([]);
  };

  // 动态获取快捷回复建议
  const fetchQuickReplySuggestions = async (userQuery: string) => {
    console.log('🎯 开始获取快捷回复建议，查询内容:', userQuery);
    
    try {
      // 调用后端Magic API获取建议
      const encodedQuery = encodeURIComponent(userQuery);
      const apiUrl = `/langchain-backend/magic/suggestions/${encodedQuery}`;
      console.log('📡 API调用URL:', apiUrl);
      
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API调用失败: ${response.status} - ${errorText}`);
      }
      
      const result = await response.json();
      
      if (result.success && result.data && result.data.suggestions) {
        // 提取建议标题作为快捷回复选项
        const suggestions = result.data.suggestions.map((suggestion: any) => suggestion.title);
        return suggestions;
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取快捷回复建议失败:', error);
      return [];
    }
  };

  // 检查消息内容并动态设置快捷回复
  const checkAndSetQuickReplies = async (advisorContent: string, userQuery?: string) => {
    // 只在收到advisor消息时生成快捷回复
    if (!advisorContent || advisorContent.trim().length === 0) {
      return;
    }

    try {
      // 使用传入的用户查询，如果没有则获取最后一条用户消息
      let query = userQuery;
      if (!query) {
        const lastUserMessage = messages
          .filter(msg => msg.type === 'user')
          .slice(-1)[0];
        query = lastUserMessage ? lastUserMessage.content : advisorContent;
      }
      
      if (!query || query.trim().length === 0) {
        return;
      }
      
      // 调用API获取建议
      const suggestions = await fetchQuickReplySuggestions(query);
      
      if (suggestions && suggestions.length > 0) {
        setCurrentQuickReplies(suggestions);
        setShowQuickReplies(true);
      }
    } catch (error) {
      console.error('生成快捷回复失败:', error);
      // 失败时不显示快捷回复，避免影响用户体验
    }
  };



  // 检查内容是否包含数字序号格式的函数
  const hasNumberedListPattern = (content: string): boolean => {
    return /^\s*\d+\.\s/.test(content);
  };

  // 纯粹的Markdown渲染器，支持UniversalCard但不显示按钮
  const ClientMarkdownRenderer = ({ content }: { content: string }) => {
    const CARD_TOKEN = /\[CARD:([^\]]+)\]/g;

    // 如果内容包含数字序号模式，按行渲染，避免markdown解析为列表
    if (hasNumberedListPattern(content)) {
      const lines = content.split('\n').filter(line => line.trim());
      
      // 用于行内markdown解析的简单函数
      const parseInlineMarkdown = (text: string) => {
        
        // 处理多种markdown格式的函数
        const processMarkdown = (str: string): React.ReactNode[] => {
          const parts: React.ReactNode[] = [];
          let remaining = str;
          let keyCounter = 0;
          
          // 匹配模式：**粗体**, *斜体*, `代码`
          const patterns = [
            { regex: /\*\*(.*?)\*\*/g, render: (content: string) => 
              <strong key={`bold-${keyCounter++}`} style={{ fontWeight: 'bold', color: '#111827' }}>{content}</strong> },
            { regex: /\*(.*?)\*/g, render: (content: string) => 
              <em key={`italic-${keyCounter++}`} style={{ fontStyle: 'italic' }}>{content}</em> }
          ];
          
          while (remaining) {
            let earliestMatch: { index: number; length: number; replacement: React.ReactNode } | null = null;
            
            // 找到最早出现的模式
            for (const pattern of patterns) {
              pattern.regex.lastIndex = 0; // 重置regex状态
              const match = pattern.regex.exec(remaining);
              if (match && (!earliestMatch || match.index < earliestMatch.index)) {
                earliestMatch = {
                  index: match.index,
                  length: match[0].length,
                  replacement: pattern.render(match[1])
                };
              }
            }
            
            if (earliestMatch) {
              // 添加匹配前的纯文本
              if (earliestMatch.index > 0) {
                parts.push(remaining.slice(0, earliestMatch.index));
              }
              // 添加格式化的内容
              parts.push(earliestMatch.replacement);
              // 更新剩余文本
              remaining = remaining.slice(earliestMatch.index + earliestMatch.length);
            } else {
              // 没有更多匹配，添加剩余文本
              parts.push(remaining);
              break;
            }
          }
          
          return parts;
        };
        
        return processMarkdown(text);
      };
      
      return (
        <div style={{ margin: '0.5em 0' }}>
          {lines.map((line, index) => {
            // 处理[CARD:xxx]标签
            if (CARD_TOKEN.test(line)) {
              const match = line.match(CARD_TOKEN);
              if (match) {
                return <UniversalCard key={index} cardContent={match[1]} />;
              }
            }
            
            // 解析行内markdown格式
            return (
              <div 
                key={index} 
                style={{ 
                  margin: '0.25em 0',
                  lineHeight: '1.5'
                }}
              >
                {parseInlineMarkdown(line)}
              </div>
            );
          })}
        </div>
      );
    }

    // 原有的markdown渲染逻辑（用于非数字序号内容）
    function renderWithCard(node: any, parentKey: string = ''): any {
      if (typeof node === 'string') {
        const parts = [];
        let lastIndex = 0;
        let match;
        let matchIndex = 0;
        while ((match = CARD_TOKEN.exec(node))) {
          if (match.index > lastIndex) {
            parts.push(node.slice(lastIndex, match.index));
          }
          const cardContent = match[1];
          const cardKey = `universalcard_${matchIndex}_${cardContent}`;
          parts.push(
            <UniversalCard key={cardKey} cardContent={cardContent} />
          );
          lastIndex = match.index + match[0].length;
          matchIndex++;
        }
        if (lastIndex < node.length) {
          parts.push(node.slice(lastIndex));
        }
        return parts.length === 1 ? parts[0] : <>{parts}</>;
      } else if (Array.isArray(node)) {
        return node.map((child, idx) => (
          <React.Fragment key={`${parentKey}_${idx}`}>
            {renderWithCard(child, `${parentKey}_${idx}`)}
          </React.Fragment>
        ));
      } else if (React.isValidElement(node)) {
        return React.cloneElement(node, (node as any).props, renderWithCard((node as any).props.children, parentKey));
      }
      return node;
    }

    return (
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          p({ children }) {
            const rendered = renderWithCard(children);
            const isAllString = (nodes: any): boolean => {
              if (typeof nodes === 'string' || nodes == null) return true;
              if (Array.isArray(nodes)) return nodes.every(isAllString);
              return false;
            };
            if (isAllString(rendered)) {
              return <p style={{ margin: '0.5em 0' }}>{rendered}</p>;
            } else {
              return <div style={{ margin: '0.5em 0' }}>{rendered}</div>;
            }
          },
          // 标题样式定义
          h1({ children }) {
            return (
              <h1 style={{ 
                fontSize: '1.5em',
                fontWeight: 'bold',
                margin: '0.8em 0 0.4em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h1>
            );
          },
          h2({ children }) {
            return (
              <h2 style={{ 
                fontSize: '1.3em',
                fontWeight: 'bold',
                margin: '0.7em 0 0.3em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h2>
            );
          },
          h3({ children }) {
            return (
              <h3 style={{ 
                fontSize: '1.2em',
                fontWeight: 'bold',
                margin: '0.6em 0 0.3em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h3>
            );
          },
          h4({ children }) {
            return (
              <h4 style={{ 
                fontSize: '1.1em',
                fontWeight: 'bold',
                margin: '0.5em 0 0.2em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h4>
            );
          },
          h5({ children }) {
            return (
              <h5 style={{ 
                fontSize: '1em',
                fontWeight: 'bold',
                margin: '0.5em 0 0.2em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h5>
            );
          },
          h6({ children }) {
            return (
              <h6 style={{ 
                fontSize: '0.9em',
                fontWeight: 'bold',
                margin: '0.5em 0 0.2em 0',
                color: '#111827',
                lineHeight: '1.3'
              }}>
                {renderWithCard(children)}
              </h6>
            );
          },
          // 无序列表样式定义（修复圆点显示）
          ul({ children }) {
            return (
              <ul style={{ 
                listStyleType: 'disc',
                paddingLeft: '1.5em',
                margin: '0.5em 0',
                listStylePosition: 'outside',
                display: 'block'
              }}>
                {children}
              </ul>
            );
          },
          li({ children }) {
            return (
              <li style={{ 
                margin: '0.25em 0',
                lineHeight: '1.5',
                display: 'list-item',
                listStyleType: 'inherit'
              }}>
                {renderWithCard(children)}
              </li>
            );
          },
          // 强调和加粗样式
          strong({ children }) {
            return (
              <strong style={{ 
                fontWeight: 'bold',
                color: '#111827'
              }}>
                {renderWithCard(children)}
              </strong>
            );
          },
          em({ children }) {
            return (
              <em style={{ 
                fontStyle: 'italic'
              }}>
                {renderWithCard(children)}
              </em>
            );
          },
          // 代码样式
          code({ children, ...props }) {
            const inline = (props as any).inline;
            if (inline) {
              return (
                <code style={{ 
                  backgroundColor: '#F3F4F6',
                  color: '#374151',
                  padding: '0.1em 0.3em',
                  borderRadius: '3px',
                  fontSize: '0.9em',
                  fontFamily: 'monospace'
                }}>
                  {children}
                </code>
              );
            } else {
              return (
                <pre style={{ 
                  backgroundColor: '#F3F4F6',
                  color: '#374151',
                  padding: '0.8em',
                  borderRadius: '6px',
                  fontSize: '0.9em',
                  fontFamily: 'monospace',
                  overflow: 'auto',
                  margin: '0.5em 0'
                }}>
                  <code>{children}</code>
                </pre>
              );
            }
          },
          span({ children }) {
            return <span>{renderWithCard(children)}</span>;
          },
        }}
      >
        {content}
      </ReactMarkdown>
    );
  };

    const selectedManagerInfo = managers.find(m => m.id === selectedManager);

  return (
    <div className="client-test-page" style={{ 
      padding: '8px', 
      backgroundColor: '#E5E7EB', 
      minHeight: '100vh',
      width: '100%',
      maxWidth: 'none',
      minWidth: '0',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      boxSizing: 'border-box',
      overflow: 'visible'
    }}>
      {/* 手机端聊天容器 */}
      <div className="mobile-chat-container" style={{ 
        width: '100%',
        maxWidth: '425px',
        minWidth: '280px',
        height: '800px',
        backgroundColor: '#fff',
        borderRadius: '28px',
        boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        margin: '0 0'
      }}>
        {/* 聊天头部 */}
        <div className="chat-header" style={{ 
          backgroundColor: '#fff', 
          color: '#000', 
          padding: '16px 20px',
          borderBottom: '1px solid #F3F4F6',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <ArrowLeftOutlined style={{ fontSize: '20px', marginRight: '16px', color: '#6B7280' }} />
            <Avatar 
              size={40} 
              src={selectedManagerInfo ? getManagerAvatar(selectedManagerInfo.id) : undefined}
              icon={selectedManagerInfo ? undefined : <UserOutlined />} 
              style={{ marginRight: '12px' }}
            />
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#111827' }}>
                  {selectedManagerInfo?.name || '请选择经理'}
                </div>
                <div 
                  style={{ 
                    width: '8px', 
                    height: '8px', 
                    borderRadius: '50%', 
                    backgroundColor: currentCustomer && isConnected ? '#10B981' : '#EF4444'
                  }}
                />
              </div>
              {selectedManagerInfo && (
                <div style={{ fontSize: '12px', color: '#6B7280', marginTop: '2px' }}>
                  理财经理
                </div>
              )}
            </div>
          </div>
          
          <Button
            type="text"
            icon={<SettingOutlined />}
            onClick={() => {
              // 打开配置前先刷新可用经理和会话列表（替代30秒定时刷新）
              fetchAvailableManagers();
              fetchExistingConversations();
              setConfigDrawerVisible(true);
            }}
            style={{
              backgroundColor: '#F3F4F6',
              color: '#6B7280',
              borderRadius: '8px',
              width: '36px',
              height: '36px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '16px'
            }}
          />
        </div>

        {/* 日期分隔符 */}
        <div style={{ 
          textAlign: 'center', 
          padding: '20px 0',
          backgroundColor: '#F9FAFB'
        }}>
          <span style={{ 
            backgroundColor: '#E5E7EB',
            color: '#6B7280',
            padding: '4px 12px',
            borderRadius: '12px',
            fontSize: '12px',
            fontWeight: '500'
          }}>
            {new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })}
          </span>
        </div>

        {/* 消息区域 */}
        <div className="messages-area" style={{ 
          flex: 1,
          overflowY: 'auto', 
          padding: '0 20px', 
          backgroundColor: '#F9FAFB'
        }}>
          {messages.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#9CA3AF', marginTop: '100px' }}>
              <UserOutlined style={{ fontSize: 32, opacity: 0.3, marginBottom: 8 }} />
              <div style={{ fontSize: '16px' }}>
                {currentCustomer && selectedManager ? 
                  `开始与${selectedManagerInfo?.name}对话吧...` : 
                  selectedManager ? 
                    '请选择客户身份开始对话...' :
                    '请配置客户和经理开始对话...'
                }
              </div>
            </div>
          ) : (
            messages.map((msg: Message) => (
              <div 
                key={msg.id} 
                style={{ 
                  marginBottom: '16px',
                  display: 'flex',
                  alignItems: 'flex-end',
                  flexDirection: msg.type === 'user' ? 'row-reverse' : 'row'
                }}
              >
                {msg.type === 'advisor' && (
                  <Avatar 
                    size={32} 
                    src={selectedManagerInfo ? getManagerAvatar(selectedManagerInfo.id) : undefined}
                    icon={selectedManagerInfo ? undefined : <UserOutlined />} 
                    style={{ marginRight: '8px', marginBottom: '4px' }}
                  />
                )}
                <div
                  style={{
                    maxWidth: '75%',
                    padding: '12px 16px',
                    borderRadius: msg.type === 'user' ? '20px 20px 6px 20px' : '20px 20px 20px 6px',
                    backgroundColor: msg.type === 'user' ? '#A855F7' : '#ffffff',
                    color: msg.type === 'user' ? 'white' : '#111827',
                    boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                    fontSize: '16px',
                    lineHeight: '1.4',
                    wordBreak: 'break-word',
                    marginLeft: msg.type === 'user' ? '8px' : '0',
                    marginRight: msg.type === 'advisor' ? '8px' : '0'
                  }}
                >
                  {msg.type === 'advisor' ? (
                    <div>
                      <ClientMarkdownRenderer content={msg.content} />
                    </div>
                  ) : (
                    msg.content
                  )}
                </div>
                {msg.type === 'user' && (
                  <Avatar 
                    size={32} 
                    src={currentCustomer ? getCustomerAvatar(currentCustomer.id, currentCustomer.name) : undefined}
                    icon={currentCustomer ? undefined : <UserOutlined />} 
                    style={{ marginLeft: '8px', marginBottom: '4px' }}
                  />
                )}
              </div>
            ))
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* 快捷回复 */}
        {showQuickReplies && (
          <div style={{ padding: '12px 20px', backgroundColor: '#F9FAFB' }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {currentQuickReplies.map((option: string, index: number) => (
                <Button
                  key={index}
                  type="default"
                  size="small"
                  icon={<StarFilled style={{ fontSize: '10px', color: '#A855F7' }} />}
                  onClick={() => handleQuickReply(option)}
                  style={{ 
                    borderRadius: '16px', 
                    fontSize: '13px',
                    height: '32px',
                    backgroundColor: '#EDE9FE',
                    borderColor: '#D8B4FE',
                    color: '#7C3AED'
                  }}
                >
                  {option}
                </Button>
              ))}
            </div>
          </div>
        )}

        {/* 输入区域 */}
        <div className="input-area" style={{ 
          padding: '16px 20px 10px', 
          backgroundColor: '#fff'
        }}>
          <div style={{ 
            display: 'flex', 
            gap: '12px', 
            alignItems: 'center',
            backgroundColor: '#F3F4F6',
            borderRadius: '24px',
            padding: '8px 10px'
          }}>
            <Input
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onPressEnter={handleKeyPress}
              placeholder={currentCustomer ? "Type something ..." : "请先选择客户..."}
              disabled={!currentCustomer}
              style={{ 
                flex: 1,
                border: 'none',
                backgroundColor: 'transparent',
                padding: '16px 0',
                fontSize: '16px',
                minHeight: '24px'
              }}
              bordered={false}
            />
            
            <Button
              type="text"
              icon={<SendOutlined />}
              onClick={handleSendMessage}
              disabled={!inputValue.trim() || !isConnected || !currentCustomer || !selectedManager}
              style={{ 
                color: inputValue.trim() && isConnected && currentCustomer && selectedManager ? '#A855F7' : '#9CA3AF',
                padding: '8px',
                minWidth: 'auto',
                height: 'auto',
                fontSize: '20px'
              }}
            />
          </div>

          {currentCustomer && isConnected && (
            <div style={{ textAlign: 'center', paddingTop: '8px' }}>
                <Text style={{ fontSize: 12, color: '#6B7280' }}>
                    您正在模拟 <Text strong style={{ color: '#4B5563' }}>{currentCustomer.name}</Text> 和理财经理对话中
                </Text>
            </div>
          )}
          {!currentCustomer && selectedManager && (
            <div style={{ textAlign: 'center', paddingTop: '8px' }}>
                <Text style={{ fontSize: 12, color: '#6B7280' }}>
                    请选择客户身份开始对话
                </Text>
            </div>
          )}
        </div>
      </div>

      {/* 配置抽屉 */}
      <Drawer
        title="配置设置"
        placement="right"
        onClose={() => setConfigDrawerVisible(false)}
        open={configDrawerVisible}
        width={320}
      >
        {/* 先选择理财经理 */}
        <div style={{ marginBottom: '24px' }}>
          <Typography.Text strong style={{ display: 'block', marginBottom: '8px' }}>
            选择理财经理
          </Typography.Text>
          <Select
            value={selectedManager}
            onChange={handleManagerChange}
            style={{ width: '100%' }}
            placeholder="选择理财师"
            optionLabelProp="label"
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.children as any)?.props?.children?.[1]?.props?.children?.[0]?.props?.children?.[0]?.toLowerCase().includes(input.toLowerCase())
            }
          >
            {managers.map(manager => {
              const hasExistingConversation = currentCustomer ? checkExistingConversation(generateWebSocketUserId(currentCustomer), manager.id) : false;
              const isDisabled = (manager.id !== selectedManager) && !manager.is_online;
              return (
                <Option
                  key={manager.id}
                  value={manager.id}
                  disabled={isDisabled}
                  label={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar size={20} src={getManagerAvatar(manager.id)} style={{ marginRight: '8px' }} />
                      <span>{manager.name}</span>
                      <div
                        style={{
                          width: '6px',
                          height: '6px',
                          borderRadius: '50%',
                          backgroundColor: manager.is_online ? '#10B981' : '#EF4444',
                          marginLeft: '6px'
                        }}
                      />
                      {hasExistingConversation && (
                        <span style={{ fontSize: '10px', color: '#EF4444', marginLeft: '4px', fontWeight: '500' }}>
                        </span>
                      )}
                    </div>
                  }
                >
                  <div style={{ display: 'flex', alignItems: 'center', padding: '8px 0', opacity: isDisabled ? 0.5 : 1 }}>
                    <Avatar size={28} src={getManagerAvatar(manager.id)} style={{ marginRight: '12px', flexShrink: 0 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: '500', fontSize: '14px', marginBottom: '2px', display: 'flex', alignItems: 'center' }}>
                        <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginRight: '6px' }}>
                          {manager.name}
                        </span>
                        <div
                          style={{
                            width: '6px',
                            height: '6px',
                            borderRadius: '50%',
                            backgroundColor: manager.is_online ? '#10B981' : '#EF4444',
                            flexShrink: 0
                          }}
                        />
                        {!manager.is_online && (
                          <span style={{ fontSize: '10px', color: '#EF4444', marginLeft: '4px', fontWeight: '500' }}>
                            (离线)
                          </span>
                        )}
                        {hasExistingConversation && (
                          <span style={{ fontSize: '10px', color: '#EF4444', marginLeft: '4px', fontWeight: '500' }}>
                          </span>
                        )}
                      </div>
                      <div style={{ fontSize: '11px', color: '#6B7280', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {manager.specialty} • 连接数: {manager.connection_count}
                      </div>
                    </div>
                  </div>
                </Option>
              );
            })}
          </Select>
        </div>

        {/* 再选择客户身份 */}
        <div style={{ marginBottom: '24px' }}>
          <Typography.Text strong style={{ display: 'block', marginBottom: '8px' }}>
            选择客户身份
          </Typography.Text>
          <Select
            value={currentCustomer?.id.toString()}
            onChange={handleUserChange}
            style={{ width: '100%' }}
            placeholder="选择客户"
            optionLabelProp="label"
            disabled={!selectedManager}
          >
            {customers.map(user => {
              const userWsId = generateWebSocketUserId(user);
              const hasExistingConversation = selectedManager && checkExistingConversation(userWsId, selectedManager);
              const isCurrentChat = currentCustomer && user.id === currentCustomer.id && selectedManager;
              const isDisabled = !isCurrentChat && hasExistingConversation;
              return (
                <Option
                  key={user.id.toString()}
                  value={user.id.toString()}
                  disabled={isDisabled}
                  label={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar size={20} src={getCustomerAvatar(user.id, user.name)} style={{ marginRight: '8px' }} />
                      <span>{user.name}</span>
                      {isCurrentChat && (
                        <span style={{ fontSize: '10px', color: '#A855F7', marginLeft: '4px', fontWeight: '500' }}>
                          (当前聊天)
                        </span>
                      )}
                      {!isCurrentChat && hasExistingConversation && (
                        <span style={{ fontSize: '10px', color: '#EF4444', marginLeft: '4px', fontWeight: '500' }}>
                        </span>
                      )}
                    </div>
                  }
                >
                  <div style={{ display: 'flex', alignItems: 'center', padding: '8px 0', opacity: isDisabled ? 0.5 : 1 }}>
                    <Avatar size={28} src={getCustomerAvatar(user.id, user.name)} style={{ marginRight: '12px', flexShrink: 0 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: '500', fontSize: '14px', marginBottom: '2px' }}>
                        {user.name}
                        {isCurrentChat && (
                          <span style={{ fontSize: '10px', color: '#A855F7', marginLeft: '6px', fontWeight: '500' }}>
                            (当前聊天)
                          </span>
                        )}
                        {!isCurrentChat && hasExistingConversation && (
                          <span style={{ fontSize: '10px', color: '#EF4444', marginLeft: '6px', fontWeight: '500' }}>
                          </span>
                        )}
                      </div>
                      <div style={{ fontSize: '11px', color: '#6B7280', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {user.occupation} • {getRiskLevelText(user)}
                      </div>
                    </div>
                  </div>
                </Option>
              );
            })}
          </Select>
        </div>

                 <div style={{ 
           padding: '16px', 
           backgroundColor: '#F9FAFB', 
           borderRadius: '8px',
           marginBottom: '24px'
         }}>
           <Typography.Text strong style={{ display: 'block', marginBottom: '8px' }}>
             连接状态
           </Typography.Text>
           <div style={{ display: 'flex', alignItems: 'center' }}>
             <div 
               style={{ 
                 width: '8px', 
                 height: '8px', 
                 borderRadius: '50%', 
                 backgroundColor: isConnected ? '#10B981' : '#EF4444',
                 marginRight: '8px',
                 flexShrink: 0
               }}
             />
             <Typography.Text type={isConnected ? 'success' : 'danger'}>
               {isConnected ? '已连接' : '未连接'}
             </Typography.Text>
           </div>
           {isConnected && currentCustomer && selectedManagerInfo && (
             <div style={{ 
               marginTop: '8px', 
               fontSize: '12px', 
               color: '#6B7280',
               whiteSpace: 'nowrap',
               overflow: 'hidden',
               textOverflow: 'ellipsis'
             }}>
               {currentCustomer.name} ↔ {selectedManagerInfo.name}
             </div>
           )}
         </div>
      </Drawer>
    </div>
  );
} 